<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsReturn;
use App\Store\Models\Goods\GoodsReturnInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Goods\GoodsTotalStockList;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\Goods;
use Illuminate\Http\Request;
use App\Store\Validate\Goods\GoodsReturn as ValidateGoodsGoodsReturn;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;

/**
 * 商品返厂
 */
class GoodsReturnController extends Controller
{
    /**
     * 商品返厂，所属门店返厂到财务部
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['type', 'goods_list', 'remark']);
        $Validate = new ValidateGoodsGoodsReturn();
        if (!$Validate->check($req_data)) {
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        //处理返厂商品列表
        $goods_list = $req_data['goods_list'];
        $return_info_data = is_array($goods_list) ? $goods_list : (is_array(json_decode($goods_list, true)) ? json_decode($goods_list, true) : []);

        DB::beginTransaction();
        try {
            $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id'], 'is_del' => 1])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }

            $goods_count = array_sum(array_column($return_info_data, 'count_new')) ?? 0;
            $order_sncode = StoreCommon::createOrderSn();
            $return_data = [
                'cp_id' => $cp_id,
                'store_id' => $store_id,
                'order_sncode' => $order_sncode,
                'goods_count' => $goods_count,
                'type' => empty($req_data['type']) ? 0 : $req_data['type'],
                'remark' => $req_data['remark'],
                'create_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
            ];

            //返厂单
            $return_id = GoodsReturn::create($return_data)->id;

            //返厂明细
            $returnArr = [];
            if ($return_info_data) {
                foreach ($return_info_data as $k => $v) {
                    $v['count_new'] = (int)$v['count_new'] ?? 1;
                    if ($v['count_new'] > $v['count']) {
                        return response()->json(['code' => '001', 'msg' => '商品返厂数量不能大于库存数量！']);
                    }

                    // 追加
                    $v['cp_id'] = $cp_id;
                    $v['store_id'] = $store_id;
                    $v['p_id'] = $return_id;
                    $v['create_account_id'] = $accountinfo['id'];
                    $v['create_account_real_name'] = $accountinfo['real_name'];
                    $v['create_at'] = time();
                    $v['order_sncode'] = $order_sncode;


                    // 一码多货的商品只有数量和总重量
                    if ($v['is_code_more'] == 2) {
                        if (empty($v['total_netglod_weight'])) {
                            return response()->json(['code' => '001', 'msg' => '一码多货商品总金重不能为空']);
                        }
                        $total_netglod_weight = $v['total_netglod_weight'];
                        $total_piece_weight = $v['piece_weight'] > 0 ? ($v['piece_weight'] * $v['count_new']) : 0;
                    } else {
                        $total_piece_weight = $v['piece_weight'] > 0 ? ($v['piece_weight'] * $v['count_new']) : 0;
                        $total_netglod_weight = $v['netglod_weight'] > 0 ? ($v['netglod_weight'] * $v['count_new']) : 0;
                    }
                    $v['total_piece_weight'] = $total_piece_weight;
                    $v['total_netglod_weight'] = $total_netglod_weight;

                    //$is_gram = $v['goods_category']['is_gram'] ?? 0;
                    //$goods = $v;
                    // $goods['count'] = $v['count_new'];
                    // $v['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($goods, $is_gram);

                    unset($v['id'], $v['allot_count'], $v['goods_brand'], $v['goods_category'], $v['goods_craft'], $v['goods_pricetype'], $v['goods_stone'], $v['goods_style'], $v['odds'], $v['paytype_info'], $v['pricetype'], $v['sales_count'], $v['start_stockin_store_id'], $v['startstoreinfo'], $v['storeinfo'], $v['supply'], $v['goods_content'], $v['goods_content_id'], $v['electronic_scale']);
                    $stock = GoodsStockList::query()
                        ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
                        ->where('goods_sn_code', $v['goods_sn_code'])
                        ->first();
                    $stock = empty($stock) ? [] : $stock->toArray();
                    // $is_gram = $category[$stock['goods_category_id']]['is_gram'] ?? 0;
                    if (empty($stock)) {
                        return response()->json(['code' => '001', 'msg' => '返厂的商品不存在']);
                    }
                    list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($stock, $v);
                    $v['total_cost_fee'] = $deduct_total_cost_fee;
                    $returnArr[] = $v;
                    $stock['count'] = $stock['count'] - $v['count_new'];
                    $stock['total_piece_weight'] = $stock['total_piece_weight'] - $total_piece_weight;
                    $stock['total_netglod_weight'] = $stock['total_netglod_weight'] - $total_netglod_weight;
                    //$total_cost_fee = (new Goods())->computeOriginalTotalCost($stock, $is_gram);

                    GoodsStockList::query()->where(['cp_id' => $cp_id, 'store_id' => $v['store_id'], 'goods_sn_code' => $v['goods_sn_code'], 'is_del' => 1])->update([
                        'count' => $stock['count'],
                        'total_piece_weight' => $stock['total_piece_weight'],
                        'total_netglod_weight' => $stock['total_netglod_weight'],
                        'total_cost_fee' => $remaining_cost_fee
                    ]);
                }
            }
            GoodsReturnInfolist::query()->insert($returnArr);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '商品返厂成功']);
    }

    /**
     * 删除
     */
    public function dopostdel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateGoodsGoodsReturn('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $store_id = (int)$accountinfo['store_ids'];

        $returnList = GoodsReturnInfolist::query()
            ->where('p_id', $req_data['id'])
            ->where('is_del', 1)
            ->get(['goods_sn_code', 'count_new', 'store_id','total_cost_fee'])
            ->pluck(null, 'goods_sn_code')
            ->toArray();
        $goodsSn = array_column($returnList, 'goods_sn_code');
        $stock = GoodsStockList::query()
            ->where('cp_id', $accountinfo['cp_id'])
            ->where('is_del', 1)
            ->where('store_id', $store_id)
            ->whereIn('goods_sn_code', $goodsSn)
            ->get()
            ->toArray();
        $category_ids = array_column($stock, 'goods_category_id');

        $category = GoodsCategory::query()
            ->where('cp_id', $accountinfo['cp_id'])
            ->where('is_del', 1)
            ->whereIn('id', $category_ids)
            ->get()
            ->pluck(null, 'id')
            ->toArray();


        try {
            DB::beginTransaction();
            if (!empty($stock)) {
                foreach ($stock as $item) {
                    $count_new = $returnList[$item['goods_sn_code']]['count_new'] ?? 0;
                    $total_piece_weight = $item['piece_weight'] * $count_new;
                    $total_netglod_weight = $item['netglod_weight'] * $count_new;
                    if ($item['is_code_more'] == 2) {
                        if (empty($item['total_netglod_weight'])) {
                            return response()->json(['code' => '001', 'msg' => '一码多货商品总金重不能为空']);
                        }
                        $total_netglod_weight = $item['total_netglod_weight'];
                    }
                    if ($count_new > 0) {
                        $is_gram = $category[$item['goods_category_id']]['is_gram'] ?? 0;

                        $incr = [
                            'total_piece_weight' => $total_piece_weight,
                            'total_netglod_weight' => $total_netglod_weight,
                            'count' => $count_new,
                            'total_cost_fee'=>$returnList[$item['goods_sn_code']]['total_cost_fee'] ?? 0,
                        ];
                        list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($item, $incr, $is_gram);
                        $item['count'] = $item['count'] + $count_new;
                        $item['total_piece_weight'] = $item['total_piece_weight'] + $total_piece_weight;
                        $item['total_netglod_weight'] = $item['total_netglod_weight'] + $total_netglod_weight;


                        // $total_cost_fee = (new Goods())->computeOriginalTotalCost($item, $is_gram);

                        GoodsStockList::where(['id' => $item['id'],'is_del' => 1])->update([
                            'count' => DB::raw('count + ' . $count_new),
                            'total_piece_weight' => DB::raw('total_piece_weight + ' . $total_piece_weight),
                            'total_netglod_weight' => DB::raw('total_netglod_weight + ' . $total_netglod_weight),
                            'total_cost_fee' => $total_cost_fee,
                            'costglod_price' => $costglod_price,
                            'piececost_fee' => $piececost_fee
                        ]);
                    }
                }
            }

            GoodsReturn::where('id', $req_data['id'])->update([
                'is_del' => 2,
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
                'update_at' => time(),
            ]);

            GoodsReturnInfolist::where('p_id', $req_data['id'])->update([
                'is_del' => 2,
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
                'update_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 导入
     * 只导入一个单子
     */
    public function doimport(Request $request)
    {
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            $return_msg = '';
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $cp_id = $accountinfo['cp_id'];
            $store_id = (int)$accountinfo['store_ids'];
            DB::beginTransaction();
            try {
                $order_sncode = StoreCommon::createOrderSn();
                $return_data = [
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'order_sncode' => $order_sncode,
                    'type' => empty($request->type) ? 0 : $request->type,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];
                $return_id = GoodsReturn::create($return_data)->id;

                if (count($data) > 1001) {
                    return response()->json(['code' => '001', 'msg' => '超过导入数据上限，最多导入1000条']);
                }

                foreach ($data as $key => $val) {
                    //表头跳过
                    if ($key == 0) {
                        continue;
                    }

                    if (empty($val)) {
                        $return_msg .= '导入失败，第【' . $key . '】行条码为空';
                    }

                    //库存查看商品信息
                    $goods = GoodsStockList::query()
                        ->where('goods_sn_code', trim($val[0]))
                        ->where('store_id', $store_id)
                        ->where('is_del', 1)
                        ->first();

                    if (!empty($goods)) {
                        $goods = $goods->toArray();

                       // print_r($goods);exit;
                        $return = $goods;

                        $return['count_new'] = trim($val[1] ?? 0);
                        $return['order_sncode'] = $order_sncode;
                        $return['cp_id'] = $cp_id;
                        $return['store_id'] = $store_id;
                        $return['p_id'] = $return_id;
                        $return['count_new'] = trim($val[1]);
                        $return['count'] = $return['count_new'];
                        $return['create_account_id'] = $accountinfo['id'];
                        $return['create_account_real_name'] = $accountinfo['real_name'];
                        $return['create_at'] = time();

                        if ((int)$goods['is_code_more'] == 2) {
                            $return['total_netglod_weight'] = trim($val[2]) ?? 0;
                            $return['total_piece_weight'] = 0;
                            if (empty($return['total_netglod_weight'])) {
                                return response()->json(['code' => '001', 'msg' => '一码多货商品总金重不能为空']);
                            }
                        } else {
                            $return['total_piece_weight'] = (int)$return['count_new'] * (float)$return['piece_weight'];
                            $return['total_netglod_weight'] = (int)$return['count_new'] * (float)$return['netglod_weight'];
                        }
//                        $category = GoodsCategory::query()
//                            ->where('cp_id', $accountinfo['cp_id'])
//                            ->where('is_del', 1)
//                            ->where('id', $goods['goods_category_id'])
//                            ->first();

//                        $category = !empty($category) ? $category->toArray() : [];
//                        if (empty($category)) {
//                            return response()->json(['code' => '000', 'msg' => $return['goods_sn_code'] . '商品类别不存在']);
//                        }

                        //  $is_gram = $category['is_gram'] ?? 0;
                        // $return['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($return, $is_gram);
                        // 删除不需要的参数
                        unset($return['id'], $return['sales_count'], $return['allot_count'], $return['start_stockin_store_id'], $return['create_at'], $return['del_at'], $return['pricetype'], $return['odds'], $return['goods_content_id'], $return['electronic_scale']);

                        list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goods, $return);
                        $return['total_cost_fee'] = $deduct_total_cost_fee;

                        $goods['count'] = $goods['count'] - $return['count_new'];

                        $goods['total_piece_weight'] = $goods['total_piece_weight'] > 0 ? bcsub($goods['total_piece_weight'], $return['total_piece_weight'],2): 0;
                        $goods['total_netglod_weight'] = $goods['total_netglod_weight'] > 0 ? bcsub($goods['total_netglod_weight'], $return['total_netglod_weight'],2) : 0;

                        // $total_cost_fee = (new Goods())->computeOriginalTotalCost($goods, $is_gram);
                        GoodsReturnInfolist::query()->create($return);

                        // 增加扣除库存
                        GoodsStockList::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'goods_sn_code' => $goods['goods_sn_code'],'is_del' => 1])
                            ->update([
                                'count' => $goods['count'],
                                'total_piece_weight' => $goods['total_piece_weight'],
                                'total_netglod_weight' => $goods['total_netglod_weight'],
                                'total_cost_fee' => $remaining_cost_fee
                            ]);
                    } else {
                        $return_msg .= '导入失败，条码【' . $key . '】，商品不存在；';
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '添加成功', 'data' => $return_msg]);
        }
        return response()->json(['code' => '001', 'msg' => '文件不存在']);
    }

    /**
     * 模板下载
     */
    public function dotemplate()
    {
        $row = [[
            'store_name' => '条码',
            'return_count' => '返厂数',
            'total_netglod_weight' => '总金重',
        ]];
        $options = [];
        $datawith = [
            'A' => '25', 'B' => '25', 'C' => '25'
        ];

        $filename = '商品返厂导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $id = $request->id ?? 0;
        $type = $request->type ?? 3;
        $ids = $request['ids'];

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $where = [];
        $order_sncode = $request->order_sncode;
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_style_id = (int)$request->goods_style_id;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = (int)$request->goods_category_id;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = (int)$request->audit_status;
        if ($audit_status > 0) {
            $where[] = ['audit_status', $audit_status];
        }

        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        // 店长、店员 不能看到成本
        $accountype =$accountinfo['type']?? 0;

        if($accountype>0&& in_array($accountype,[1,2])){
            $total_cost_feeTemp =[];
        }else{
            $total_cost_feeTemp=['total_cost_fee'=>'总成本'];
        }

        if ($type == 1) {
            $query = GoodsReturnInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_category_id', $ids);
            }

            $list = $query->groupBy('goods_category_id')
                ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
                ->get()->toArray();

            $row = [
                ['table_header' => '返厂汇总'],
                [
                    'audit_status' => '状态',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'goods_style' => '款式',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]+$total_cost_feeTemp];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count_new'] ? '审核' : '审核中'),
                    'category_name' => $val['goods_category']['category_name'],
                    'category_name1' => $val['goods_category']['category_name'],
                    'goods_style' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                    'total_cost_fee'=>$val['total_cost_fee']>0? ($val['total_cost_fee'] / 100): '',
                ];
            }
        } elseif ($type == 2) {
            $query = GoodsReturnInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_style_id', $ids);
            }

            $list = $query->groupBy('goods_style_id')
                ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
                ->get()->toArray();

            $row = [
                ['table_header' => '按款式汇总'],
                [
                    'audit_status' => '状态',
                    'goods_style' => '款式',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]+$total_cost_feeTemp
            ];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count_new'] ? '审核' : '审核中'),
                    'goods_style' => $val['goods_style'] ? $val['goods_style']['style_name'] : '--',
                    'category_name' => '--',
                    'category_name1' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                    'total_cost_fee'=>$val['total_cost_fee']>0? ($val['total_cost_fee'] / 100): '',
                ];
            }
        } else {
            // 传入ids，数组

            $list = GoodsReturnInfolist::getExportList($request)['list'];
            if($accountype>0&& in_array($accountype,[1,2])){
                $row = [
                    ['table_header' => '返厂明细'],
                    [
                        'store' => '起始门店',
                        'goods_brand_name' => '品牌',
                        'category_name' => '入库类别',
                        'category_name_2' => '商品类别',
                        'goods_img' => '商品图片',
                        'goods_sn_code' => '条码',
                        'goods_name' => '品名',
                        'style_name' => '款式',
                        'label_price' => '入库标签价',
                        'label_price_new' => '标签售价',
                        'piece_weight' => '入库重量',
                        'piece_weight_new' => '重量',
                        'netglod_weight' => '入库金重',
                        'netglod_weight_new' => '金重',
                        'total_piece_weight' => '入库总重量', //piece_weight*count
                        'total_piece_weight_new' => '总重量', //piece_weight_new*count
                        'gramprice_fee' => '克销工费',
                        'pieceprice_fee' => '件销工费',
                        'content' => '含量',
                        'count' => '库存数量',
                        'count_new' => '返厂数量',
                        'allot_count' => '调拨数量',
                        'cf_no' => '证书号',
                        'cf_no_gia' => 'GIA证书号',
                        'main_stone_weigth' => '主石重',
                        'main_stone_count' => '主石数',
                        'main_stone_val' => '主石值',
                        'other_stone_weigth' => '副石重',
                        'other_stone_count' => '副石数',
                        'other_stone_val' => '副石值',
                        'color' => '颜色',
                        'clarity' => '净度',
                        'cut' => '切工',
                    ]];
            }else{
                $row = [
                    ['table_header' => '返厂明细'],
                    [
                        'store' => '起始门店',
                        'goods_brand_name' => '品牌',
                        'category_name' => '入库类别',
                        'category_name_2' => '商品类别',
                        'goods_img' => '商品图片',
                        'goods_sn_code' => '条码',
                        'goods_name' => '品名',
                        'style_name' => '款式',
                        'label_price' => '入库标签价',
                        'label_price_new' => '标签售价',
                        'piece_weight' => '入库重量',
                        'piece_weight_new' => '重量',
                        'netglod_weight' => '入库金重',
                        'netglod_weight_new' => '金重',
                        'total_piece_weight' => '入库总重量', //piece_weight*count
                        'total_piece_weight_new' => '总重量', //piece_weight_new*count
                        'gramprice_fee' => '克销工费',
                        'pieceprice_fee' => '件销工费',
                        'costglod_price' => '金价',
                        'costpiece_fee' => '件成本工费',
                        'costgram_fee' => '克成本工费',
                        'piececost_fee' => '单件成本',
                        'total_fee' => '总成本',
                        'content' => '含量',
                        'count' => '库存数量',
                        'count_new' => '返厂数量',
                        'allot_count' => '调拨数量',
                        'cf_no' => '证书号',
                        'cf_no_gia' => 'GIA证书号',
                        'main_stone_weigth' => '主石重',
                        'main_stone_count' => '主石数',
                        'main_stone_val' => '主石值',
                        'other_stone_weigth' => '副石重',
                        'other_stone_count' => '副石数',
                        'other_stone_val' => '副石值',
                        'color' => '颜色',
                        'clarity' => '净度',
                        'cut' => '切工',
                    ]];
            }


            $is_store_account = StoreCommon::getIsStoreAccount($request);
            if (!$is_store_account) {
                unset($row[0]['supply_name']);
                unset($row[0]['paymoney']);
                unset($row[0]['costglod_price']);
                unset($row[0]['total_fee']);
                unset($row[0]['piececost_fee']);
                unset($row[0]['piececost_fee_total']);
            }

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'store' => $val['storeinfo']['store_name'],
                    'goods_brand_name' => $val['goods_brand']['brand_name'] ?? '',
                    'category_name' => $val['goods_category']['category_name'],
                    'category_name_2' => $val['goods_category']['category_name'],
                    'goods_img' => $val['goods_img'],
                    'goods_sn_code' => $val['goods_sn_code'],
                    'goods_name' => $val['goods_name'],
                    'style_name' => $val['goods_style']['style_name'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'piece_weight' => $val['piece_weight'],
                    'piece_weight_new' => $val['piece_weight_new'],
                    'netglod_weight' => $val['netglod_weight'],
                    'netglod_weight_new' => $val['netglod_weight_new'],
                    'total_piece_weight' => $val['total_piece_weight'] ?? 0, //piece_weight*count
                    'total_piece_weight_new' => $val['total_piece_weight_new'] ?? 0, //piece_weight_new*count
                    'gramprice_fee' => $val['gramprice_fee'] / 100,
                    'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                    'costglod_price' => $val['costglod_price'] / 100,
                    'costpiece_fee' => $val['costpiece_fee'] / 100,
                    'costgram_fee' => $val['costgram_fee'] / 100,
                    'piececost_fee' => $val['piececost_fee']>0?($val['piececost_fee'] / 100) :'',
                    'total_fee' => $val['total_cost_fee']>0?($val['total_cost_fee'] / 100) :'',
                    'content' => $val['content'],
                    'count' => $val['count'],
                    'count_new' => $val['count_new'],
                    'allot_count' => $val['allot_count'],
                    'cf_no' => $val['cf_no'],
                    'cf_no_gia' => $val['cf_no_gia'],
                    'main_stone_weigth' => $val['main_stone_weigth'],
                    'main_stone_count' => $val['main_stone_count'],
                    'main_stone_val' => $val['main_stone_val'],
                    'other_stone_weigth' => $val['other_stone_weigth'],
                    'other_stone_count' => $val['other_stone_count'],
                    'other_stone_val' => $val['other_stone_val'],
                    'color' => $val['color'],
                    'clarity' => $val['clarity'],
                    'cut' => $val['cut'],
                ];
            }
        }

        $filename = '商品返厂信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $request['store_ids'] = $accountinfo['store_ids'];
        $list = GoodsReturn::getList($request);
        //统计明细中商品数、审核数、驳回数、应付账款
        if ($list) {
            $pids = array_column($list['list'], 'id');
            $retuenInfo = GoodsReturnInfolist::query()
                ->where('is_del', 1)
                ->whereIn('p_id', $pids)
                ->selectRaw('p_id,SUM(count_new)as goods_count,SUM(paymoney)as paymoney')
                ->groupBy('p_id')
                ->get()
                ->pluck(null, 'p_id')
                ->toArray();

            $review = GoodsReturnInfolist::query()
                ->where('is_del', 1)
                ->whereIn('p_id', $pids)
                ->where('audit_status', 2)
                ->selectRaw('p_id,SUM(count_new)as review_num')
                ->groupBy('p_id')
                ->get()
                ->pluck(null, 'p_id')
                ->toArray();

            $reject = GoodsReturnInfolist::query()
                ->where('is_del', 1)
                ->whereIn('p_id', $pids)
                ->where('audit_status', 3)
                ->selectRaw('p_id,SUM(count_new)as review_num')
                ->groupBy('p_id')
                ->get()
                ->pluck(null, 'p_id')
                ->toArray();

            foreach ($list['list'] as &$val) {

                $val['goods_count'] = (int)($retuenInfo[$val['id']]['goods_count'] ?? 0);
                //审核成功
                $val['review_num'] = (int)($review[$val['id']]['review_num'] ?? 0);
                //审核取消
                $val['reject_num'] = (int)($reject[$val['id']]['reject_num'] ?? 0);
                //应付账款
                $val['total_paymoney'] = (int)($retuenInfo[$val['id']]['paymoney'] ?? 0);
            }
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 查看明细
     */
    public function getinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsReturn::with(['storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info['total_count_new'] = GoodsReturnInfolist::where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->select(DB::raw('sum(count_new) as count_new'))->first()->toArray()['count_new'];

        $where = [];
        $goods_sn_code = $request->order_sncode ?? '';
        if ($goods_sn_code != '') {
            $where[] = ['goods_sn_code', 'like', '%' . $goods_sn_code . '%'];
        }

        $goods_style_id = $request->goods_style_id ?? 0;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = $request->audit_status ?? 0;

        $list1_new = $list2_new = [];
        //按照类别汇总
        $list1 = GoodsReturnInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list1) {
            foreach ($list1 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count_new']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count_new']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1_new = array_values($list1);
        }

        //按照款式汇总
        $list2 = GoodsReturnInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where)
            ->groupBy('goods_style_id')
            ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list2) {
            foreach ($list2 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count_new']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count_new']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list2[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list2[$k]);
                    }
                }
            }
            $list2_new = array_values($list2);
        }

        //查询子订单详情
        $list3_query = GoodsReturnInfolist::with(['storeinfo', 'brand', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where);
        if ($audit_status > 0) {
            $list3_query->where('audit_status', $audit_status);
        }
        $list3 = $list3_query->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1_new, 'list2' => $list2_new, 'list3' => $list3]]);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        // 待操作的明细
        if (count($goods_category_ids) > 0) {
            $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }
        if (empty($infolist)) {
            return response()->json(['code' => '001', 'msg' => '未查到返厂数据']);
        }

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                GoodsReturnInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_success_count' => $info['count_new'], 'audit_at' => time()]);

                // 明细审核状态
                $audit_status_count = GoodsReturnInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }


                // 审核成功数
                GoodsReturn::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'is_del' => 1])->increment('audit_success_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 21返厂出库
                Goods::goodsLog($request, $info['store_id'], 0, $info, $info['count_new'], 21, $info['order_sncode']);
                $is_gram = GoodsCategory::query()
                    ->where(['id' => $info['goods_category_id'], 'cp_id' => $cp_id, 'is_del' => 1])
                    ->value('is_gram') ?? 0;
                // 返厂到总库存
                unset($info['id']);
                $data = $info;
                $data['count'] = $info['count_new'];

                if ($info['is_code_more'] == 2) {
                    $data['total_netglod_weight'] = $info['total_netglod_weight'];
                } else {
                    $data['total_piece_weight'] = $info['count_new'] * $info['piece_weight'];
                    $data['total_netglod_weight'] = $info['count_new'] * $info['netglod_weight'];
                }

                $total_cost_fee = (new Goods())->computeOriginalTotalCost($data, $is_gram);
                $data['total_cost_fee'] = $total_cost_fee;
                $data['create_at'] = time();

                GoodsTotalStockList::query()->create($data);

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '返厂单审核成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (count($goods_category_ids) > 0) {
            $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsReturnInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }


        $store_ids = array_column($infolist, 'store_id');

        $goods_sn = array_column($infolist, 'goods_sn_code');


        $stockList = GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->whereIn('store_id', $store_ids)
            ->get()
            ->pluck(null, 'goods_sn_code')
            ->toArray();


        $category_ids = array_column($stockList, 'goods_category_id');
        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->where('is_del', 1)
            ->whereIn('id', $category_ids)
            ->get()
            ->pluck(null, 'id')
            ->toArray();


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsReturnInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count_new'], 'audit_at' => time()]);
                $audit_status_count = GoodsReturnInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 审核取消数
                GoodsReturn::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_failed_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 22取消返厂
                Goods::goodsLog($request, 0, $info['store_id'], $info, $info['count_new'], 22, $info['order_sncode']);

                $stock = $stockList[$info['goods_sn_code']] ?? [];
                if (empty($stock)) {
                    return response()->json(['code' => '001', 'msg' => '商品' . $info['goods_sn_code'] . '不存在']);
                }

                $cate = $category[$stock['goods_category_id']] ?? [];

                if (empty($cate)) {
                    return response()->json(['code' => '001', 'msg' => '商品' . $info['goods_sn_code'] . '类别不存在']);
                }

                $is_gram = $cate['is_gram'] ?? 0;
                list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stock, $info, $is_gram);

                $stock['count'] = $stock['count'] + $info['count_new'];
                $stock['total_piece_weight'] = $stock['total_piece_weight'] + $info['total_piece_weight'];
                $stock['total_netglod_weight'] = $stock['total_netglod_weight'] + $info['total_netglod_weight'];
                //  $total_cost_fee = (new Goods())->computeOriginalTotalCost($stock, $is_gram);
                GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info['store_id'], 'goods_sn_code' => $info['goods_sn_code'],'is_del' => 1])->update([
                    'count' => $stock['count'],
                    'total_piece_weight' => $stock['total_piece_weight'],
                    'total_netglod_weight' => $stock['total_netglod_weight'],
                    'total_cost_fee' => $total_cost_fee,
                    'costglod_price' => $costglod_price,
                    'piececost_fee' => $piececost_fee
                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '返厂单审核取消成功']);
    }

    /**
     * 批量审核
     */
    public function doauditsuccessmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择需要审核的商品']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        if (!in_array($accountinfo['type'], [9])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用管理端进行审核']);
        }

        $maininfocount = GoodsReturn::where(['cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->count();

        if ($maininfocount != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核商品']);
        }

        $infolist = GoodsReturnInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1])->whereIn('p_id', $ids)->get()->toArray();

        if (empty($infolist)) {
            return response()->json(['code' => '001', 'msg' => '未查到返厂数据']);
        }

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                GoodsReturnInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_success_count' => $info['count_new'], 'audit_at' => time()]);

                // 明细审核状态
                $audit_status_count = GoodsReturnInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                // 审核成功数
                GoodsReturn::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_success_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 21返厂出库
                Goods::goodsLog($request, $info['store_id'], 0, $info, $info['count_new'], 21, $info['order_sncode']);

                // 返厂到总库存
                unset($info['id']);
                $data = $info;

                $is_gram = GoodsCategory::query()
                    ->where(['id' => $info['goods_category_id'], 'cp_id' => $cp_id, 'is_del' => 1])
                    ->value('is_gram') ?? 0;
                $data['count'] = $info['count_new'];
                if ($info['is_code_more'] == 2) {
                    $data['total_netglod_weight'] = $info['total_netglod_weight'];
                } else {
                    $data['total_piece_weight'] = $data['count'] * $info['piece_weight'];
                    $data['total_netglod_weight'] = $data['count'] * $info['netglod_weight'];

                }

                $total_cost_fee = (new Goods())->computeOriginalTotalCost($data, $is_gram);
                $data['total_cost_fee'] = $total_cost_fee;
                $data['create_at'] = time();
                GoodsTotalStockList::query()->create($data);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '返厂审核成功']);
    }

    /**
     * 撤审
     */
    public function doauditcancelmore(Request $request)
    {
        $p_ids = $request->ids;
        $p_ids = is_array($p_ids) ? $p_ids : (is_array(json_decode($p_ids, true)) ? json_decode($p_ids, true) : []);


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [9])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用管理端进行审核']);
        }

        $maininfo_arr = GoodsReturn::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('audit_status', [1, 2])->whereIn('id', $p_ids)->count();

        if ($maininfo_arr != count($p_ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $infolist = GoodsReturnInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])
            ->whereIn('p_id', $p_ids)
            ->get()
            ->toArray();

        $store_ids = array_column($infolist, 'store_id');
        $goods_sn = array_column($infolist, 'goods_sn_code');
        $stockList = GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->whereIn('store_id', $store_ids)
            ->get()
            ->pluck(null, 'goods_sn_code')
            ->toArray();


        $category_ids = array_column($stockList, 'goods_category_id');
        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->where('is_del', 1)
            ->whereIn('id', $category_ids)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsReturnInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_failed_count' => $info['count_new'], 'audit_at' => time()]);
                $audit_status_count = GoodsReturnInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1, 'is_del' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 审核取消数
                GoodsReturn::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'is_del' => 1])->increment('audit_failed_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 22取消返厂
                Goods::goodsLog($request, 0, $info['store_id'], $info, $info['count_new'], 22, $info['order_sncode']);

                $stock = $stockList[$info['goods_sn_code']] ?? [];
                if (empty($stock)) {
                    return response()->json(['code' => '000', 'msg' => '商品' . $info['goods_sn_code'] . '不存在']);
                }

                $cate = $category[$stock['goods_category_id']] ?? [];
                if (empty($cate)) {
                    return response()->json(['code' => '000', 'msg' => $info['goods_sn_code'] . '商品类别不存在']);
                }


                $is_gram = $cate['is_gram'] ?? 0;

                list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stock, $info, $is_gram);
                $stock['count'] = $stock['count'] + $info['count_new'];
                $stock['total_piece_weight'] = $stock['total_piece_weight'] + $info['total_piece_weight'];
                $stock['total_netglod_weight'] = $stock['total_netglod_weight'] + $info['total_netglod_weight'];
                // $total_cost_fee = (new Goods())->computeOriginalTotalCost($stock, $is_gram);

                GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info['store_id'], 'goods_sn_code' => $info['goods_sn_code'],'is_del' => 1])->update([
                    'count' => $stock['count'],
                    'total_piece_weight' => $stock['total_piece_weight'],
                    'total_netglod_weight' => $stock['total_netglod_weight'],
                    'total_cost_fee' => $total_cost_fee,
                    'costglod_price' => $costglod_price,
                    'piececost_fee' => $piececost_fee

                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '返厂审核取消成功']);
    }
}
